import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import api, { type UserInfo, type LoginRequest, type QuizResult, type QuizQuestion } from '~/api'

// 用户相关的composable
export const useUser = () => {
  const userInfo = ref<UserInfo | null>(null)
  const isLoading = ref(false)
  const isLoggedIn = ref(false)

  // 登录
  const login = async (loginData: LoginRequest) => {
    try {
      isLoading.value = true
      const response = await api.user.login(loginData)
      
      if (response.data) {
        userInfo.value = response.data.userInfo
        isLoggedIn.value = true
        
        // 保存到本地存储
        if (process.client) {
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
        }
        
        return response.data
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await api.user.logout()
      
      userInfo.value = null
      isLoggedIn.value = false
      
      // 清除本地存储
      if (process.client) {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
      }
      
      ElMessage.success('已退出登录')
    } catch (error) {
      console.error('登出失败:', error)
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await api.user.getUserInfo()
      if (response.data) {
        userInfo.value = response.data
        isLoggedIn.value = true
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 更新用户信息
  const updateUserInfo = async (data: Partial<UserInfo>) => {
    try {
      isLoading.value = true
      const response = await api.user.updateUserInfo(data)
      
      if (response.data) {
        userInfo.value = response.data
        
        // 更新本地存储
        if (process.client) {
          localStorage.setItem('userInfo', JSON.stringify(response.data))
        }
      }
      
      return response.data
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 初始化用户状态
  const initUser = () => {
    if (process.client) {
      const savedUserInfo = localStorage.getItem('userInfo')
      const token = localStorage.getItem('token')
      
      if (savedUserInfo && token) {
        userInfo.value = JSON.parse(savedUserInfo)
        isLoggedIn.value = true
      }
    }
  }

  return {
    userInfo: readonly(userInfo),
    isLoading: readonly(isLoading),
    isLoggedIn: readonly(isLoggedIn),
    login,
    logout,
    fetchUserInfo,
    updateUserInfo,
    initUser
  }
}

// 测试相关的composable
export const useQuiz = () => {
  const questions = ref<QuizQuestion[]>([])
  const currentResult = ref<QuizResult | null>(null)
  const userResults = ref<QuizResult[]>([])
  const isLoading = ref(false)

  // 获取测试题目
  const fetchQuestions = async (category?: string) => {
    try {
      isLoading.value = true
      const response = await api.quiz.getQuestions(category)
      
      if (response.data) {
        questions.value = response.data
      }
      
      return response.data
    } catch (error) {
      console.error('获取题目失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 提交答案
  const submitAnswers = async (category: string, answers: any[]) => {
    try {
      isLoading.value = true
      const response = await api.quiz.submitAnswers({ category, answers })
      
      if (response.data) {
        currentResult.value = response.data
      }
      
      return response.data
    } catch (error) {
      console.error('提交答案失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户测试结果
  const fetchUserResults = async () => {
    try {
      isLoading.value = true
      const response = await api.quiz.getUserResults()
      
      if (response.data) {
        userResults.value = response.data
      }
      
      return response.data
    } catch (error) {
      console.error('获取测试结果失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 生成报告
  const generateReport = async () => {
    try {
      isLoading.value = true
      const response = await api.quiz.generateReport()
      
      return response.data
    } catch (error) {
      console.error('生成报告失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 下载报告
  const downloadReport = async (reportId: number) => {
    try {
      await api.quiz.downloadReport(reportId)
      ElMessage.success('报告下载成功')
    } catch (error) {
      console.error('下载报告失败:', error)
      ElMessage.error('下载报告失败')
    }
  }

  return {
    questions: readonly(questions),
    currentResult: readonly(currentResult),
    userResults: readonly(userResults),
    isLoading: readonly(isLoading),
    fetchQuestions,
    submitAnswers,
    fetchUserResults,
    generateReport,
    downloadReport
  }
}

// 文件上传相关的composable
export const useFileUpload = () => {
  const isUploading = ref(false)
  const uploadProgress = ref(0)

  // 上传文件
  const uploadFile = async (file: File, type: 'image' | 'document' = 'image') => {
    try {
      isUploading.value = true
      uploadProgress.value = 0
      
      const response = await api.file.upload(file, type)
      
      if (response.data) {
        uploadProgress.value = 100
        ElMessage.success('文件上传成功')
        return response.data
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      ElMessage.error('文件上传失败')
      throw error
    } finally {
      isUploading.value = false
      setTimeout(() => {
        uploadProgress.value = 0
      }, 1000)
    }
  }

  // 上传头像
  const uploadAvatar = async (file: File) => {
    try {
      isUploading.value = true
      const response = await api.user.uploadAvatar(file)
      
      if (response.data) {
        ElMessage.success('头像上传成功')
        return response.data
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      throw error
    } finally {
      isUploading.value = false
    }
  }

  // 删除文件
  const deleteFile = async (fileUrl: string) => {
    try {
      await api.file.delete(fileUrl)
      ElMessage.success('文件删除成功')
    } catch (error) {
      console.error('文件删除失败:', error)
      ElMessage.error('文件删除失败')
    }
  }

  return {
    isUploading: readonly(isUploading),
    uploadProgress: readonly(uploadProgress),
    uploadFile,
    uploadAvatar,
    deleteFile
  }
}

// 统计数据相关的composable
export const useStats = () => {
  const userStats = ref<{
    totalTests: number
    completedTests: number
    averageScore: number
    lastTestDate: string
    categories: {
      name: string
      count: number
      averageScore: number
    }[]
  } | null>(null)
  
  const systemStats = ref<{
    totalUsers: number
    totalTests: number
    activeUsers: number
    popularCategories: string[]
  } | null>(null)
  
  const isLoading = ref(false)

  // 获取用户统计
  const fetchUserStats = async () => {
    try {
      isLoading.value = true
      const response = await api.stats.getUserStats()
      
      if (response.data) {
        userStats.value = response.data
      }
      
      return response.data
    } catch (error) {
      console.error('获取用户统计失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取系统统计
  const fetchSystemStats = async () => {
    try {
      isLoading.value = true
      const response = await api.stats.getSystemStats()
      
      if (response.data) {
        systemStats.value = response.data
      }
      
      return response.data
    } catch (error) {
      console.error('获取系统统计失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  return {
    userStats: readonly(userStats),
    systemStats: readonly(systemStats),
    isLoading: readonly(isLoading),
    fetchUserStats,
    fetchSystemStats
  }
}